/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import control.ShopFacade;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Callback;
import jfxtras.labs.scene.control.BeanPathAdapter;
import jpamodel.Seller;

/**
 *
 * @author Hans
 */
public class SellersView extends VBox {

    private Seller selectedSeller;
    private final TableView<Seller> table = new TableView<>();
    private ObservableList<Seller> sellers;// = FXCollections.observableArrayList ();
    private final TableColumn<Seller, String> name;
    private final TableColumn<Seller, String> phone;
    private final TableColumn<Seller, Number> money;
    private ShopFacade shop;
    private final Text text;
    private final GridPane editingGrid = new GridPane();
    private Button payOut, editPhone, editAddress, deleteSeller;
    private TextField newPhone, newAddress;
    private Label sellerName;

    public SellersView(ObservableList<Seller> data, ShopFacade shop) {
        this.money = new TableColumn<>("Tilgodehavende");
        this.phone = new TableColumn<>("Telefon");
        this.name = new TableColumn<>("Navn");
        this.sellers = data;
        Seller seller = new Seller();
        BeanPathAdapter<Seller> sellerAdapter = new BeanPathAdapter<>(seller);
        sellerAdapter.bindContentBidirectional("name", null, String.class, table.getItems(), null, null, null);
        sellerAdapter.bindContentBidirectional("phone", null, String.class, table.getItems(), null, null, null);
        sellerAdapter.bindContentBidirectional("money", null, Number.class, table.getItems(), null, null, null);
        name.setCellValueFactory(new PropertyValueFactory<>("name"));
        phone.setCellValueFactory(new PropertyValueFactory<>("phone"));
        money.setCellValueFactory(new PropertyValueFactory<>("money"));
        this.shop = shop;
        this.setPadding(MainView.INSETS);
        this.text = new Text("* Sælgere *");
        text.setFont(MainView.getFont());
        table.getColumns().add(name);
        table.getColumns().add(phone);
        table.getColumns().add(money);
        name.prefWidthProperty().bind(table.widthProperty().multiply(0.40));
        phone.prefWidthProperty().bind(table.widthProperty().multiply(0.30));
        money.prefWidthProperty().bind(table.widthProperty().multiply(0.30));
        phone.getStyleClass().add("numbercolums");
        money.getStyleClass().add("numbercolums");
        name.setCellFactory(TextFieldTableCell.forTableColumn());
        name.setOnEditCommit(t -> {
            Seller s = t.getRowValue();
            s.setName(t.getNewValue());
            shop.persist(s);
            sellerAdapter.setBean(s);
        });
        phone.setCellFactory(TextFieldTableCell.forTableColumn());
        phone.setOnEditCommit(t -> {
            Seller s = t.getRowValue();
            s.setPhone(t.getNewValue() + "");
            shop.persist(s);
            sellerAdapter.setBean(s);
        });
        Callback<TableColumn<Seller, Number>, TableCell<Seller, Number>> cellFactory
                = (TableColumn<Seller, Number> p) -> new EditingCell();
        money.setCellFactory(cellFactory);
        money.setOnEditCommit(t -> {
            Seller s = t.getRowValue();
            s.setMoney(t.getNewValue().intValue());
            shop.persist(s);
            sellerAdapter.setBean(s);
        });
//        name.setCellValueFactory(c -> c.getValue().nameProperty());
//        //    address.setCellValueFactory((TableColumn.CellDataFeatures<Seller, String> param) -> new SimpleObjectProperty(param.getValue().getAdress()));
//        phone.setCellValueFactory(c -> c.getValue().phoneProperty());
//        money.setCellValueFactory(c -> c.getValue().moneyProperty());
        money.setMinWidth(130);
        table.setPrefWidth(MainView.WIDTH);
        table.setItems(sellers);
        this.getChildren().addAll(text, table, editingGrid);
        setupButtons();
        table.getStyleClass().add("table");

        table.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> selectedSeller(newValue));

        table.setEditable(true);
    }

    private void setupButtons() {
        editingGrid.setHgap(7);
        editingGrid.setVgap(3);
        sellerName = new Label(" ");
        payOut = new Button("Udbetal Penge");
        editPhone = new Button("Ret Telefon Nr");
//        editAddress = new Button("Ret Adresse");
        deleteSeller = new Button("Slet Sælger");
        newPhone = new IntegerTextField();
//        newAddress = new TextField();
        editingGrid.addRow(0, sellerName);
        editingGrid.addRow(1, payOut);
        editingGrid.addRow(2, editPhone, newPhone);
//        editingGrid.addRow(3, editAddress, newAddress);
        editingGrid.addRow(4, deleteSeller);

        payOut.getStyleClass().add("mybutton");
        payOut.setOnAction(event -> {
            if (selectedSeller != null) {
                selectedSeller.setMoney(0);
                shop.persist(selectedSeller);
            }
        });

//        editAddress.getStyleClass().add("mybutton");
//        editAddress.setOnAction(event -> {
//            if (selectedSeller != null) {
//                selectedSeller.setAdress(newAddress.getText());
//                newAddress.clear();
//                datalist.set(datalist.indexOf(selectedSeller), selectedSeller);
//            }
//        });
        editPhone.getStyleClass().add("mybutton");
        editPhone.setOnAction(event -> {
            if (selectedSeller != null && !newPhone.getText().trim().isEmpty()) {
                selectedSeller.setPhone(newPhone.getText());
                newPhone.clear();
                shop.persist(selectedSeller);
            }
        });

        deleteSeller.getStyleClass().add("mybutton");
        deleteSeller.setOnAction(event -> {
            if (selectedSeller != null) {
                shop.remove(selectedSeller);
                sellers.remove(selectedSeller);
            }
        });
    }

    void update() {
        if (shop.getDBC().isConnected()) {
            sellers.removeAll(shop.getAllSellers());
            sellers.clear();
            sellers.addAll(shop.getAllSellers());
            table.setItems(sellers);
        }
        table.getColumns().get(0).setVisible(false);
        table.getColumns().get(0).setVisible(true);
    }

    private void selectedSeller(Seller newValue) {
        if (newValue != null) {
            selectedSeller = newValue;
        }
    }

    class EditingCell extends TableCell<Seller, Number> {

        private TextField textField;
        private String numericLastKey;

        public EditingCell() {
            this.addEventFilter(KeyEvent.KEY_TYPED, (KeyEvent event) -> {
                char ar[] = event.getCharacter().toCharArray();
                char ch = ar[event.getCharacter().toCharArray().length - 1];
                /*populating lastkey if it is numeric*/
                if ((ch >= '0' && ch <= '9')) {
                    numericLastKey = String.valueOf(ch);
                }

                if (isValid()) {
                    /* Disable other charater than numeric character. */
                    if (!(ch >= '0' && ch <= '9')) {
                        event.consume();
                    }
                } else {
                    event.consume();
                }
            });
        }

        @Override
        public void startEdit() {
            super.startEdit();

            if (textField == null) {
                createTextField();
            }
            textField.setStyle("-fx-font-size: 9pt;-fx-padding:1px 1px 1px 1px;-fx-border-insets: 0;-fx-border-width: 2px;-fx-background-color: pink;");
            setGraphic(textField);
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

            Platform.runLater(() -> {
                textField.requestFocus();
                textField.selectAll();
            });
        }

        @Override
        public void cancelEdit() {
            super.cancelEdit();

            setText(String.valueOf(getItem()));
            setContentDisplay(ContentDisplay.TEXT_ONLY);
        }

        @Override
        public void updateItem(Number item, boolean empty) {
            super.updateItem(item, empty);

            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    if (textField != null) {
                        textField.setText(getString());
                    }
                    setGraphic(textField);
                    setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                } else {
                    setText(getString());
                    setContentDisplay(ContentDisplay.TEXT_ONLY);
                }
            }
        }

        private void createTextField() {
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
            textField.setOnKeyPressed(t -> {
                if (t.getCode() == KeyCode.ENTER) {
                    commitEdit(Integer.parseInt(textField.getText()));
                } else if (t.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                }
            });
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }

        private boolean isValid() {
            if (getText().length() == 0) {
                return true;
            }
            try {
                String testText = getText();
                testText = (numericLastKey != null && !"".equals(numericLastKey)) ? testText + numericLastKey : testText;
                numericLastKey = "";
                Integer.parseInt(testText);
            } catch (NumberFormatException ex) {
                return false;
            }
            return true;
        }
    }

}//end of class
